
import { Listbox, ListboxItem, ScrollShadow, Avatar, Button } from "@nextui-org/react";
import { Team } from "@/type/team";
import { PlusIcon } from "../../TableView";
import { unicodeToEmoji } from "@/utils/randomemoji";
import { useAppSelector } from "@/lib/hooks";
import { selectUserDetail } from "@/lib/features/login/loginSlice";
import { apply } from "@/api/team/apply";
import toast from "react-hot-toast";

export const ListboxWrapper = ({ children }: { children: React.ReactNode }) => (
    <div className="w-full px-1 py-2 rounded-small">
        <ScrollShadow className="max-h-[300px] ">
            {children}
        </ScrollShadow>

    </div>
);

export default function TeamList({ teams, onCloseCurrent }: { teams: Team[], onCloseCurrent: () => void }) {

    const { user_id } = useAppSelector(selectUserDetail)

    return (
        <ListboxWrapper>
            <Listbox
                items={teams}
                emptyContent={
                    <>
                        <p className="text-center">无搜索目标</p>
                    </>
                }
                variant="flat"
            >

                {(item) => (
                    <ListboxItem key={item.team_id} textValue={item.team_name}>
                        <div className="flex gap-2 justify-between items-center">
                            <div className="flex gap-2 items-center">
                                <Avatar icon={<span className="text-2xl">{unicodeToEmoji(item.emoji ?? 0x1F680)}</span>} radius="md" color="warning" />
                                <div className="flex flex-col">
                                    <span className="text-small">{item.team_name}</span>
                                </div>
                            </div>
                            <Button onPress={async () => {
                                const result = await apply(user_id as number, item.team_id as number)
                                console.log(result);
                                if (result.code == 200) {
                                    toast.success(result.message)
                                } else {
                                    toast.error(result.message)
                                }
                                onCloseCurrent()
                            }} isIconOnly size="sm" color="primary">
                                <PlusIcon />
                            </Button>
                        </div>
                    </ListboxItem>
                )}

            </Listbox>
        </ListboxWrapper>
    );
}
